import React, { Component } from 'react'
import './tree.scss'
import PropTypes from 'prop-types';
import Checkbox from './../checkbox/index'

export default class TreeNode extends Component {
  constructor(props) {
    super(props)
    this.state = {
      isSemi: false,
      childrenNode: []
    }
    this.getRoot = this.getRoot.bind(this)
    this.getStore = this.getStore.bind(this)
    this.getSlotRender = this.getSlotRender.bind(this)
  }

  getRoot () {
    return this.context.TreeRoot
  }

  getChildContext () {
    return {
      TreeNode: this
    }
  }

  componentDidMount () {
    if (this.context.TreeNode) {
      this.context.TreeNode.state.childrenNode.push(this)
    } else {
      this.getRoot().state.childrenNode.push(this)
    }
    this.getStore().mountedSemi(this)
  }

  getStore () {
    return this.getRoot().state.store
  }

  getSlotRender () {
    if (this.getRoot().props.renderFn) {
      return this.getRoot().props.renderFn(this.props.data)
    } else {
      return (
        <span>{this.props.data.name}</span>
      )
    }
  }

  onClick (e) {
    e.stopPropagation();
  }

  onCheckedChange (val) {
    this.getRoot().onCheckedChange(this, val)
  }

  render () {
    return (
      <li onClick={this.onClick.bind(this)} className="tbcTreeLi">
        <Checkbox
        isSemi={this.state.isSemi}
        checked={this.props.data.checked}
        onChange={this.onCheckedChange.bind(this)}>
          {this.getSlotRender()}
        </Checkbox>
        {
          this.props.data.children ?
          <ul>
            {
              this.props.data.children.map((u, index) => {
                return(
                  <TreeNode data={u} key={index}></TreeNode>
                )
              })
            }
          </ul>
          :
          ''
        }
      </li>
    )
  }

}

TreeNode.contextTypes = {
  TreeRoot: PropTypes.any,
  TreeNode: PropTypes.any
}

TreeNode.childContextTypes = {
  TreeNode: PropTypes.any
}